from rest_framework import serializers
from django.contrib.auth.models import User
from ..models import Document
from .category import CategorySerializer
from .tag import TagSerializer

class UserSerializer(serializers.ModelSerializer):
    """用户序列化器"""
    class Meta:
        model = User
        fields = ['id', 'username', 'email']

class DocumentListSerializer(serializers.ModelSerializer):
    """文档列表序列化器"""
    category = CategorySerializer(read_only=True)
    
    class Meta:
        model = Document
        fields = ['id', 'title', 'slug', 'description', 'category',
                 'views', 'created_at']

class DocumentSerializer(serializers.ModelSerializer):
    """文档序列化器"""
    category = CategorySerializer(read_only=True)
    tags = TagSerializer(many=True, read_only=True)
    author = UserSerializer(read_only=True)

    class Meta:
        model = Document
        fields = ['id', 'title', 'slug', 'description', 'content',
                 'category', 'tags', 'author', 'views', 'is_published',
                 'created_at', 'updated_at']
        read_only_fields = ['views', 'created_at', 'updated_at']

class DocumentDetailSerializer(DocumentSerializer):
    """文档详情序列化器"""
    class Meta(DocumentSerializer.Meta):
        pass

class DocumentSearchSerializer(DocumentListSerializer):
    """文档搜索结果序列化器"""
    highlight = serializers.SerializerMethodField()

    class Meta(DocumentListSerializer.Meta):
        fields = DocumentListSerializer.Meta.fields + ['highlight']

    def get_highlight(self, obj):
        if hasattr(obj, 'meta'):
            return {
                'title': getattr(obj.meta.highlight, 'title', []),
                'content': getattr(obj.meta.highlight, 'content', [])
            }
        return None 